import 'package:flutter_chat/common/utils/utils.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:get/get.dart';

/// 通知服务
class NotificationService extends GetxService {
  static NotificationService get to => Get.find();

  final FlutterLocalNotificationsPlugin _notification =
      FlutterLocalNotificationsPlugin();

  /// 初始化
  Future<NotificationService> init() async {
    var android = const AndroidInitializationSettings("@mipmap/ic_launcher");
    var ios = const DarwinInitializationSettings();

    await _notification.initialize(
      InitializationSettings(android: android, iOS: ios),
      onDidReceiveNotificationResponse: onDidReceiveNotificationResponse,
    );

    /// 获取通知权限
    _notification
        .resolvePlatformSpecificImplementation<
            AndroidFlutterLocalNotificationsPlugin>()
        ?.requestNotificationsPermission();

    return this;
  }

  /// 点击通知回调事件
  void onDidReceiveNotificationResponse(NotificationResponse response) {
    LogUtil.p("点击通知回调事件");
  }

  /// 发送通知
  Future<void> show(String title, String body, {String? payload}) async {
    // 安卓的通知
    // 'your channel id'：用于指定通知通道的ID。
    // 'your channel name'：用于指定通知通道的名称。
    // 'your channel description'：用于指定通知通道的描述。
    // Importance.max：用于指定通知的重要性，设置为最高级别。
    // Priority.high：用于指定通知的优先级，设置为高优先级。
    // 'ticker'：用于指定通知的提示文本，即通知出现在通知中心的文本内容。
    const AndroidNotificationDetails androidNotificationDetails =
        AndroidNotificationDetails(
      '1',
      '消息通知',
      channelDescription: '用于实时获取用户通知',
      importance: Importance.max,
      priority: Priority.max,
      ticker: 'ticker',
    );

    // ios的通知
    const String darwinNotificationCategoryPlain = 'plainCategory';
    const DarwinNotificationDetails iosNotificationDetails =
        DarwinNotificationDetails(
      categoryIdentifier: darwinNotificationCategoryPlain, // 通知分类
    );
    // 创建跨平台通知
    const NotificationDetails platformChannelSpecifics = NotificationDetails(
      android: androidNotificationDetails,
      iOS: iosNotificationDetails,
    );

    // 发起一个通知
    await _notification.show(
      DateTime.now().millisecondsSinceEpoch >> 10,
      title,
      body,
      platformChannelSpecifics,
      payload: payload,
    );
  }

  ///清除所有通知
  void cleanNotification() {
    _notification.cancelAll();
  }

  /// 清除指定通知
  void cleanNotificationById(int id, {String? tag}) {
    _notification.cancel(id, tag: tag);
  }
}
